package com.study.controller;

import com.study.service.MovieUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.study.dao.entity.MovieUser;


@RestController
public class MovieUserController {
	
	@Autowired
	RestTemplate restTemplate;
	
	@Autowired
	LoadBalancerClient LoadBalancerClient;

	@Autowired
	MovieUserService movieUserService;

	/*
		http://localhost:8082/ribbon/actuator/health

		http://localhost:8082/ribbon/ribbon/1
	 */
	@GetMapping("/ribbon/{id}")
	@HystrixCommand(fallbackMethod = "selectByIdFallback")
	public MovieUser selectById(@PathVariable("id") int id) {
		//spring.application.name=sunxj-microservice-provider-user
		//vip=virtual ip
		System.out.println("ribbon thread: " + Thread.currentThread().getName());
		MovieUser movieUser = restTemplate.getForObject("http://sunxj-microservice-provider-user/simple/" + id, MovieUser.class);
		return movieUser;
	}

	@GetMapping("/test-thread/{id}")
	public MovieUser testThread(@PathVariable("id") int id) {
		System.out.println("ribbon thread: " + Thread.currentThread().getName());
		MovieUser movieUser = movieUserService.selectById(id);
		return movieUser;
	}

	@GetMapping("/test-thread2/{id}")
	public MovieUser testThread2(@PathVariable("id") int id) throws InterruptedException {
		System.out.println("ribbon thread: " + Thread.currentThread().getName());
		MovieUser movieUser = movieUserService.selectById2(id);
		System.out.println("123");
		return movieUser;
	}

	@GetMapping("/test-thread3/{id}")
	public MovieUser testThread3(@PathVariable("id") int id) {
		for(int i=0; i<15; i++) {
			Thread t  = new Thread(new Runnable() {
				@Override
				public void run() {
					MovieUser movieUser = movieUserService.selectById(id);
					System.out.println("ribbon thread: " + Thread.currentThread().getName() + ": " + movieUser);

				}
			},"thread " + i);
			t.start();
		}
		MovieUser movieUser = movieUserService.selectById(id);
		return movieUser;
	}

	public MovieUser selectByIdFallback(int id) {
		//spring.application.name=sunxj-microservice-provider-user
		//vip=virtual ip
		MovieUser movieUser = new MovieUser();
		movieUser.setId(0);
		return movieUser;
	}

}
